package com.sinopec.basemodule.adapter;

import android.app.Activity;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sinopec.basemodule.AppConstants;
import com.sinopec.basemodule.R;
import com.sinopec.basemodule.model.ImageBean;
import com.sinopec.basemodule.utils.AndroidLifecycleUtils;
import com.sinopec.basemodule.view.PhotoPreview;

import java.util.ArrayList;

public class PhotoOnlineAdapter extends RecyclerView.Adapter<PhotoOnlineAdapter.PhotoViewHolder> {

    private ArrayList<ImageBean> images;
    private LayoutInflater inflater;
    private Activity activity;

    public PhotoOnlineAdapter(Activity activity, ArrayList<ImageBean> images) {
        this.images = images;
        this.activity = activity;
        inflater = LayoutInflater.from(activity);
    }

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.item_image, parent, false);
        return new PhotoViewHolder(itemView);
    }


    @Override
    public void onBindViewHolder(@NonNull final PhotoViewHolder holder, final int position) {
        ImageBean imageBean = images.get(position - 1);
        Uri uri = Uri.parse(AppConstants.IMAGE_SEVER + imageBean.getNetPath());
        boolean canLoadImage = AndroidLifecycleUtils.canLoadImage(holder.ivPhoto.getContext());
        if (canLoadImage) {
            final RequestOptions options = new RequestOptions();
            options.centerCrop()
                    .placeholder(R.drawable.picker_ic_photo_black_48dp)
                    .error(R.drawable.picker_ic_broken_image_black_48dp);
            Glide.with(activity)
                    .load(uri)
                    .apply(options)
                    .thumbnail(0.1f)
                    .into(holder.ivPhoto);
        }
        holder.itemView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                holder.itemView.performClick();
            }
            return true;
        });
        holder.itemView.setOnClickListener(v -> {
            PhotoPreview.builder()
                    .setPhotos(images)
                    .setCurrentItem(position)
                    .start(activity);
        });
    }


    @Override
    public int getItemCount() {
        return images.size();
    }

    static class PhotoViewHolder extends RecyclerView.ViewHolder {
        private ImageView ivPhoto;

        PhotoViewHolder(View itemView) {
            super(itemView);
            ivPhoto = itemView.findViewById(R.id.iv_photo);
        }
    }
}
